<?php
/*
 * @Description: 
 * @Author: Leequik
 * @Date: 2025-07-27 18:12:19
 * @LastEditTime: 2025-07-28 00:52:05
 * @LastEditors: Leequik
 */
namespace App\Services;
use App\Events\SendMessageEvent;
use Illuminate\Support\Facades\Log;
use App\Events\TestEvent;
use App\Models\Company;
use App\Models\TaskLog;
use Illuminate\Database\Eloquent\Collection;



class SendMessageService
{
    /**
     * 发送消息
     *
     * @param string $argType
     * @param string $expire
     * @param string $msg
     * @return void
     */

    public function send(string $msg): void{
        
        //$this->test();

        $this->timeoutToMinuteWarning();
       
    }

    public function test(){

        // $argType = 'XDJ';
        // $expire = '1';
        // $msg = '发欺诈超时警告！';

        // // 触发事件
        // event(new TestEvent($argType,$expire,$msg));

        //  // 记录日志
        //  Log::info('SendMessageService: Message sent', [
        //     'msg' => $msg,
        // ]);

        $this->timeoutToMinuteWarning();
        
    }

    //查询company表中的数据，执行警报任务
    public function timeoutToMinuteWarning(){
        //获取5分钟前到1分钟前创建的活跃公司数据
        $startDate = now()->subMinutes(50);
        $endDate = now()->subMinutes(1);

        $company = Company::active()
        ->where(function ($query) use ($startDate, $endDate) {
            $query->whereBetween('fraud_verif_time', [$startDate, $endDate])
                  ->orWhereNull('fraud_verif_time');
        })
        ->get();
        //->toSql();
        if ($company) {
            $type = 1;
            $this->sendMessage($type,$company);
        }

        
    
      
    }

    //发送消息
    public function sendMessage($type,Collection $collect)
    {
        $taskLogArr = [];
        if (isset($collect) && !empty($collect)) {
            foreach ($collect as $item) {

                if (!$item instanceof Company) {
                    continue; // 确保每个项都是Company实例
                }

                // 检查在task_log表中是否有存在，存在则结束循环
                //只检查当前10分钟内的数据
                $existingLog = TaskLog::where('source_id', $item->id)
                    //->where('status', 1) // 1表示已处理
                    ->where('application_number', $item->application_number) // 确保任务名称匹配
                    //->where('created_at', '<=', now()->subMinutes(30)) // 只检查最近10分钟内的记录
                    ->get();
                if ($existingLog->isNotEmpty()) {
                 
                    Log::info('Task log already exists for company ID: ' . $item->id);
                    continue; // 如果已存在，则跳过当前项
                }
               

                // 触发事件
                $company_id = $item->id;
                $user_id = $item->user_id;
                $application_number = $item->application_number;
                $company_name = $item->company_name;
                $source_id = $item->id;
                $message = "公司名称: {$company_name}, 申请号: {$application_number}, 公司ID: {$company_id}，请注意欺诈超时警告！"; 

                $taskLogArr[] = [
                    'user_id' => $user_id,
                    'company_id' => $company_id,
                    'application_number' => $application_number,
                    'source_id' => $source_id, // 关联的公司ID
                    'request_data' => $message, // 请求数据
                ];
                //event(new SendMessageEvent($type, $message));
                event(new TestEvent($type, 2,$message));
            
                //$this->sendMsg();
            }
            if (!empty($taskLogArr)) {
                $this->logTask($taskLogArr);
            }
            
        }
        
        
        
        
    }

    /**
     * 记录任务日志
     *
     * @param string $msg
     * @return void
     */

    //入库
    public function logTask(array $taskLogArr)
    { 
        //dd($taskLogArr);
        try {
            // 批量入库
            TaskLog::insert(array_map(function ($taskLogArr) {
                return [
                    'user_id' => $taskLogArr['user_id'],
                    'company_id' => $taskLogArr['company_id'],
                    'application_number' => $taskLogArr['application_number'],
                    'status' => 1, // 0表示未处理
                    'frequency' => 1, // 1表示每分钟
                    'source_id' =>$taskLogArr['source_id'], // 关联的公司ID
                    'request_data' => $taskLogArr['request_data'], // 请求数据
                    'created_at' => now(), // 当前时间
                    'updated_at' => now(), // 当前时间
                ];
            }, $taskLogArr));

            Log::info('Task logs inserted successfully.');

        } catch (\Exception $e) {
            Log::error('Failed to insert task logs: ' . $e->getMessage());
        }
           
    }


}